package com.jiuan.oa.android.library.util;


import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES处理工具类
 */
public final class AESUtil {

    private static final String AES_ECB_MODE = "AES/ECB/PKCS5Padding";

    private static final String CHARSET = "UTF-8";

    public static String encrypt(final String password, String message) throws GeneralSecurityException {
        try {
            final SecretKeySpec key = generateKey(password);
            byte[] cipherText = encrypt(key, message.getBytes(CHARSET));
            return Base64.encodeToString(cipherText, Base64.NO_WRAP);
        } catch (UnsupportedEncodingException e) {
            throw new GeneralSecurityException(e);
        }
    }

    public static String decrypt(final String password, String base64EncodedCipherText) throws GeneralSecurityException {
        try {
            final SecretKeySpec key = generateKey(password);
            byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.NO_WRAP);
            byte[] decryptedBytes = decrypt(key, decodedCipherText);
            return new String(decryptedBytes, CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new GeneralSecurityException(e);
        }
    }

    private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        byte[] key = password.getBytes();
        return new SecretKeySpec(key, "AES");
    }

    private static byte[] encrypt(final SecretKeySpec key, final byte[] message) throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_ECB_MODE);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(message);
    }

    private static byte[] decrypt(final SecretKeySpec key, final byte[] decodedCipherText) throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_ECB_MODE);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(decodedCipherText);
    }

    private AESUtil() {
    }
}

